<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="排班日期" style="width: 308px">
        <el-date-picker v-model="daterangeScheduleDate" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="时间段" prop="time">
        <el-select v-model="queryParams.time" placeholder="请选择时间段" clearable>
          <el-option v-for="dict in time" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="科室" prop="departmentId">
        <el-select v-model="queryParams.departmentId" placeholder="请选择科室" clearable>
          <el-option v-for="dict in td_department" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增周历导航 -->
    <div class="week-control">
      <el-button icon="ArrowLeft" circle @click="changeWeek(-1)"></el-button>
      <div class="current-week">{{ currentWeekRange }}</div>
      <el-button icon="ArrowRight" circle @click="changeWeek(1)"></el-button>
    </div>

    <!-- 周历视图 -->
    <div class="calendar-week">
      <div v-for="day in weekDays" :key="day.date" class="calendar-day"
        :class="{ 'disabled-day': isPastDate(day.date) }" @click.stop="handleDayClick(day)">
        <div class="day-header">
          <div class="weekday">{{ day.weekDay }}</div>
          <div class="date">{{ day.date.split('-').slice(1).join('-') }}</div>
        </div>
        <div class="schedule-content">
          <div v-for="schedule in day.schedules" :key="schedule.id" class="schedule-item">
            <div class="top-line">
              <el-tag size="small">{{ timeFormat(schedule.time) }}</el-tag>
              <span class="department">{{ getDepartmentName(schedule.departmentId) }}</span>
            </div>
            <div class="bottom-line">
              <span class="doctor">{{ schedule.docterName }}</span>
              <span class="count">号源：{{ schedule.count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 原有弹窗 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="schedulelistRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="排班日期" prop="scheduleDate">
          <el-date-picker clearable v-model="form.scheduleDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择排班日期" :disabled-date="disabledDate" :disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时间段" prop="time">
          <el-select v-model="form.time" placeholder="请选择时间段">
            <el-option v-for="dict in time" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择科室">
            <el-option v-for="dict in departmentlist" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="form.departmentId && docterlist.length > 0">
          <el-form-item label="医生" prop="docterId">
            <el-select v-model="form.docterId" placeholder="请选择医生" clearable @change="onDocterChange">
              <el-option v-for="dict in docterlist" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="号源" prop="count">
          <el-input v-model="form.count" placeholder="请输入号源" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Schedulelist">
import {
  listSchedulelist,
  getSchedulelist,
  delSchedulelist,
  addSchedulelist,
  updateSchedulelist,
  docterlistbydept,
  listDepartment,
} from "@/api/schedule/schedulelist";
import { ref, reactive, getCurrentInstance, computed, onMounted, watch } from "vue";

const { proxy } = getCurrentInstance();
const { time, td_department } = proxy.useDict("time", "td_department");

// 周历相关数据
const currentDate = ref(new Date());
const weekDays = ref([]);

// 业务数据
const schedulelistList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeScheduleDate = ref([]);
const docterlist = ref([]);
const departmentlist = ref([]);

const data = reactive({
  form: {
    id: null,
    docterId: null,
    docterName: null,
    scheduleDate: null,
    time: null,
    createTime: null,
    departmentId: null,
    count: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    docterId: null,
    docterName: null,
    scheduleDate: null,
    time: null,
    departmentId: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

// 周历方法
const generateWeekDays = () => {
  const start = new Date(currentDate.value);
  start.setDate(start.getDate() - start.getDay() + 1);
  weekDays.value = Array.from({ length: 7 }).map((_, i) => {
    const date = new Date(start);
    date.setDate(date.getDate() + i);
    return {
      date: proxy.parseTime(date, "{y}-{m}-{d}"),
      weekDay: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][i],
      schedules: []
    };
  });
};

// 在script setup中添加部门名称转换方法
const getDepartmentName = (departmentId) => {
  return td_department.value.find(item => item.value == departmentId)?.label || '未知科室';
};

const currentWeekRange = computed(() => {
  const start = weekDays.value[0]?.date || '';
  const end = weekDays.value[6]?.date || '';
  return `${start} - ${end}`;
});

const changeWeek = (offset) => {
  currentDate.value.setDate(currentDate.value.getDate() + offset * 7);
  generateWeekDays();
  loadScheduleData();
};

const loadScheduleData = () => {
  const params = {
    beginScheduleDate: weekDays.value[0].date,
    endScheduleDate: weekDays.value[6].date
  };

  listSchedulelist({
    ...queryParams.value,
    params
  }).then(res => {
    weekDays.value.forEach(day => {
      day.schedules = res.rows.filter(item => item.scheduleDate === day.date);
    });
  });
};

const handleDayClick = (day) => {
  if (isPastDate(day.date)) return;
  handleAdd();
  proxy.$nextTick(() => {
    form.value.scheduleDate = day.date;
    form.value.departmentId = null;
    form.value.docterId = null;
    form.value.time = null;
    form.value.count = null;
  });
};

const isPastDate = (dateString) => {
  const selectedDate = new Date(dateString).setHours(0, 0, 0, 0);
  const today = new Date().setHours(0, 0, 0, 0);
  return selectedDate < today;
};

const timeFormat = (value) => {
  return time.value.find(item => item.value == value)?.label || '';
};

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 86400000; // 禁用今天以前的所有日期
};

// /** 查询排班信息列表 */
// function getList() {
//   loading.value = true;
//   queryParams.value.params = {};
//   if (null != daterangeScheduleDate && "" != daterangeScheduleDate) {
//     queryParams.value.params["beginScheduleDate"] =
//       daterangeScheduleDate.value[0];
//     queryParams.value.params["endScheduleDate"] =
//       daterangeScheduleDate.value[1];
//   }
//   listSchedulelist(queryParams.value).then((response) => {
//     schedulelistList.value = response.rows;
//     total.value = response.total;
//     loading.value = false;
//   });
// }

// //获取科室信息
// function getDepartmentList() {
//   listDepartment().then((response) => {
//     departmentlist.value = response.map((item) => ({
//       label: item.departmentName,
//       value: item.departmentId,
//     }));
//     loading.value = false;
//   });
// }

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    docterId: null,
    docterName: null,
    scheduleDate: null,
    time: null,
    createTime: null,
    departmentId: null,
    count: null,
  };
  proxy.resetForm("schedulelistRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeScheduleDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加排班信息";
  getDepartmentList();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getSchedulelist(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改排班信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulelistRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateSchedulelist(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSchedulelist(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认删除该排班信息？")
    .then(function () {
      return delSchedulelist(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "schedule/schedulelist/export",
    {
      ...queryParams.value,
    },
    `schedulelist_${new Date().getTime()}.xlsx`
  );
}

/** 选择医生更新表单 */
const onDocterChange = (value) => {
  const selectedDocter = docterlist.value.find((item) => item.value === value);
  if (selectedDocter) {
    form.value.docterName = selectedDocter.label; // 更新医生姓名
  } else {
    form.value.docterName = null; // 如果没有找到，清空医生姓名
  }
};

watch(
  () => form.value.departmentId,
  (val) => {
    docterlistbydept({
      departmentId: val,
    }).then((response) => {
      docterlist.value = response.map((item) => ({
        label: item.docterName,
        value: item.docterId,
      }));
    });
  }
);


// getList();

function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (daterangeScheduleDate.value?.length === 2) {
    queryParams.value.params["beginScheduleDate"] = daterangeScheduleDate.value[0];
    queryParams.value.params["endScheduleDate"] = daterangeScheduleDate.value[1];
  }
  listSchedulelist(queryParams.value).then((response) => {
    schedulelistList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getDepartmentList() {
  listDepartment().then((response) => {
    departmentlist.value = response.map((item) => ({
      label: item.departmentName,
      value: item.departmentId,
    }));
  });
}

// 其他原有方法保持不变（handleQuery、resetQuery、submitForm等）

onMounted(() => {
  generateWeekDays();
  loadScheduleData();
  getDepartmentList();
});

watch(() => queryParams.value, () => {
  loadScheduleData();
}, { deep: true });

watch(
  () => form.value.departmentId,
  (val) => {
    docterlistbydept({ departmentId: val }).then((response) => {
      docterlist.value = response.map((item) => ({
        label: item.docterName,
        value: item.docterId,
      }));
    });
  }
);
</script>

<style scoped>
.week-control {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 0;
  gap: 15px;
}

.current-week {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.calendar-week {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  gap: 10px;
  padding: 10px 0;
  margin-top: 20px;
}

/* 固定卡片宽度并禁止收缩 */
.calendar-day {
  width: 280px;
  /* 固定宽度 */
  min-width: 280px;
  /* 最小宽度保持相同 */
  flex-shrink: 0;
  /* 禁止宽度收缩 */
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 12px;
  min-height: 200px;
  background: #fff;
  transition: all 0.3s;
  cursor: pointer;
}

.calendar-day:hover {
  transform: translateY(-3px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.disabled-day {
  background-color: #f5f7fa;
  cursor: not-allowed;
  opacity: 0.6;
}

.disabled-day:hover {
  transform: none;
  box-shadow: none;
}

.day-header {
  text-align: center;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px dashed #eee;
}

.weekday {
  font-size: 14px;
  color: #909399;
}

.date {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-top: 4px;
}

.schedule-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.schedule-item {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 8px;
}

.time-badge {
  margin-bottom: 8px;
  /* 增加下边距分隔时间段和医生信息 */
}

.time-badge {
  flex-shrink: 0;
}

.schedule-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  /* 减小间距 */
}

.department {
  font-weight: 500;
  color: #409EFF !important;
  /* 使用主题色突出显示 */
}

/* 调整医生信息字体大小 */
.doctor {
  font-size: 13px;
  color: #303133;
}

/* 调整号源显示样式 */
.count {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.schedule-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* 新增样式 */
.schedule-item {
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 8px;
}

.top-line {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.department {
  font-size: 12px;
  color: #666;
  line-height: 1;
}

.bottom-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
}

.doctor {
  color: #303133;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.count {
  color: #409EFF;
  font-weight: 500;
  flex-shrink: 0;
}

/* 调整时间标签样式 */
:deep(.el-tag) {
  height: 24px;
  padding: 0 6px;
}
</style>
